<?php
define('IN_PHPBB', true);
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
require($phpbb_root_path . 'common.' . $phpEx);
require($phpbb_root_path . 'includes/functions_user.' . $phpEx);
require($phpbb_root_path . 'includes/functions_module.' . $phpEx);

$user->session_begin();
$auth->acl($user->data);
$user->setup('ucp');

$userTemplateData = include 'facebook_user_config.php';

require_once '../../../libs/facebook/facebook.php';
$facebook = new Facebook(array(
  'appId'  => '333131460108054',
  'secret' => '1f95d997d8bdab38d442b61304cfea75',
  'fileUpload' => true
));

$userID = $_POST['userID'];
$accessToken = $_POST['accessToken'];


$facebook->setAccessToken($accessToken);
$fbuser = $facebook->api('/me', array(
                  'fields' => 'picture, first_name, last_name, name, email, birthday, gender, hometown',
                  'type'   => 'large'
              ));

$hometown = "";

if($fbuser['hometown']) {
    $hometown = $fbuser['hometown']['name'];
}

$bigPicture     = $fbuser['picture'];

if(isset($bigPicture['data'])){
    $bigPicture = $bigPicture['data']['url'];
}        

$birthday = "";
if($fbuser['birthday']) {
    $birthdays = explode("/", $fbuser['birthday']);
    $birthday = "{$birthdays[1]}-{$birthdays[0]}-{$birthdays[2]}";
}

$userTemplateData['username'] = str_replace(" ", "_", strtolower($fbuser['name']));
$userTemplateData['username_clean'] = str_replace(" ", "_", strtolower($fbuser['name']));
$userTemplateData['user_email'] = $fbuser['email'];
$userTemplateData['user_birthday'] = $birthday;
$userTemplateData['user_sig'] = serialize($fbuser);

// check if current user is registered or not
$checkSQL = "select * from " . USERS_TABLE . " where user_email = '{$fbuser['email']}'";
$result = $db->sql_query($checkSQL);
$user_row = $db->sql_fetchrow($result);
if(!$user_row) {
//    if ($user->data['is_registered'])
//    {
//        redirect(append_sid("{$phpbb_root_path}index.$phpEx"));
//    }
//
//    login_box(request_var('redirect', "index.$phpEx"));
    
    // register this user and then login
    $db->sql_multi_insert(USERS_TABLE, $userTemplateData);
    $db->sql_transaction('commit');
    
    // then login again
    $checkSQL = "select * from " . USERS_TABLE . " where user_email = '{$fbuser['email']}'";
    $result = $db->sql_query($checkSQL);
    $user_row = $db->sql_fetchrow($result);
}

$user->session_create($user_row['user_id']);
//$data =  $auth->login("phamhphuc", "phamhphuc");

$return = array(
    'redirect' => append_sid("{$phpbb_root_path}index.$phpEx"),
    'status' => 1
); 
echo json_encode($return);